from django.shortcuts import render,HttpResponse,redirect,reverse,get_object_or_404,get_list_or_404
from rbac.models import Role
from rbac.forms.role import RoleModelForm
# print('rbac list')
#
# # def role_list(request):
# #     return HttpResponse('ok fuk')

def role_list(request):
    """
    角色列表功能
    :param request:
    :return:
    """
    object_list=Role.objects.all()
    # print(object_list)
    context = {
        'objects':object_list,
    }
    return render(request, 'rbac/role_list.html', context)


def role_add(request):
    form=RoleModelForm()
    if request.method == "POST":
        form = RoleModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse('rbac:role_list'))
    context = {
        'form':form,
    }
    return render(request,'rbac/change.html',context)


def role_edit(request,pk):
    obj = get_object_or_404(Role, pk=pk)
    if request.method == 'GET':
        form = RoleModelForm(instance=obj)
        return render(request, 'rbac/change.html', {'form': form})
    form = RoleModelForm(data=request.POST, instance=obj)
    if form.is_valid():
        form.save()
        return redirect(reverse('rbac:role_list'))
    return render(request, 'rbac/change.html', {'form': form})


def role_del(request, pk):
    origin_url = reverse('rbac:role_list')
    if request.method == "GET":
        return render(request, 'rbac/delete.html', {'cancel': origin_url})
    Role.objects.filter(pk=pk).delete()
    return redirect(origin_url)
